<template>
  <div class="custom-table-container">
    <table class="custom-table">
      <thead>
        <tr>
          <th>#</th>
          <th>{{ title }}</th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="(row, index) in tableData"
          :key="row.id"
          :class="{ 'selected': row.selected }"
          @mouseover="handleHover(row, index)"
          @mouseleave="handleMouseLeave(row, index)"
          @click="handleClick(row, index)"
          :style="{ backgroundImage: `url(${getRowBackground(row, index)})`, height: rowHeight + 'px' }"
        >
          <td>{{ row.id }}</td>
          <td>{{ row.name }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: "CustomTable",
  props: {
    title: {
      type: String,
      default: "列表",
    },
    tableData: {
      type: Array,
      required: true, // 表格数据由外部传递
    },
    rowHeight: {
      type: Number,
      default: 50, // 设置行高
    },
  },
  data() {
    return {
      hoverIndex: null, // 用于记录悬停的行
    };
  },
  methods: {
    handleHover(row, index) {
      this.hoverIndex = index; // 记录当前悬停的行
    },
    handleMouseLeave(row, index) {
      this.hoverIndex = null; // 悬停离开时清空
    },
    handleClick(row, index) {
      // 切换选中状态，确保只有一行选中
      this.$emit(
        "update:tableData",
        this.tableData.map((item, i) => ({
          ...item,
          selected: i === index ? !item.selected : false, // 只允许一个行被选中
        }))
      );

      // 传递选中的行数据给父组件
      if (!row.selected) {
        this.$emit('row-selected', row);
      }
    },
    getRowBackground(row, index) {
      if (row.selected) {
        return require('@/assets/img/test/tablerow1.png'); // 选中效果的背景图
      } else if (this.hoverIndex === index) {
        return require('@/assets/img/test/tablerow2.png'); // 悬停效果的背景图
      } else {
        return row.backgroundImage; // 默认背景图
      }
    },
  },
};
</script>

<style scoped>
.custom-table-container {
  width: 100%;
}

.custom-table {
  width: 100%;
  border-collapse: collapse;
}

.custom-table th, .custom-table td {
  padding: 10px;
  text-align: left;
  color: white;
}

.custom-table tbody tr {
  background-size: cover;
  background-position: center;
  transition: background-color 0.3s ease; /* 平滑过渡效果 */
}

.custom-table tbody tr.selected {
  /* 高亮选中行的样式 */
  background-color: rgba(0, 123, 255, 0.5);
}
</style>
